package com.example.test.advice.第八章_异常.建议113_不要在finally块中处理返回值;

import java.util.zip.DataFormatException;

/**
 * finally的会产生的作用
 * 1、覆盖了try catch中的return返回值
 * 2、屏蔽异常
 */
public class Client {

    public static void main(String[] args) {
        try {
            int i = doStuff(-1);
            System.out.println("i:"+i);
            int j = doStuff(100);
            System.out.println("j："+j);
            int k = doStuff();
            System.out.println("k:"+k);
            Person person = doStuffPerson();
            System.out.println("name："+person.getName());
        } catch (Exception e) {
            System.out.println("这里是永远不会到达的");
        }
    }

    //该方法抛出受检查异常
    public static int doStuff(int _p) throws Exception{
        try {
            if(_p<0){
                throw new DataFormatException("数据格式错误");
            }else {
                return _p;
            }
        }catch (Exception e){
            //异常处理
            throw e;
        }finally {
            return -1;
        }
    }

    //永远返回1
    public static int doStuff(){
        int a = 1;
        try {
            return a;
        }catch (Exception e){

        }finally {
            //重新修改下返回值
            a = -1;
        }

        return 0;
    }

    //永远返回李四，因为return的是Person对象的引用
    public static Person doStuffPerson(){
        Person person = new Person();
        person.setName("张三");
        try {
            return person;
        }catch (Exception e){

        }finally {
            person.setName("李四");
        }
        person.setName("王五");
        return person;
    }

}

class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
